﻿using log4net;
using ServerControl.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServerControl.Dal
{
	public class FeedbackDal : DbBase
	{
		private static ILog logger = LogManager.GetLogger("FeedbackDal");

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="feedback"></param>
		/// <returns></returns>
		public static bool Insert(Feedback feedback)
		{
			if (!Instance
				.Queryable<Feedback>()
				.Where(f => f.TypeId == feedback.TypeId && f.Imei == feedback.Imei && f.Remark == feedback.Remark)
				.Any())
			{
				return Instance.Insertable(feedback).ExecuteCommand() > 0;
			}

			return true;
		}

		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public static bool Delete(int id, string userName)
		{
			return Instance
					.Deleteable<Feedback>()
					.Where(g => g.Id == id && g.UserName == userName)
					.ExecuteCommand() > 0;
		}

		public static bool Delete(List<int> ids, string userName)
		{
			return Instance
					.Deleteable<Feedback>()
					.Where(g => ids.Contains(g.Id) && g.UserName == userName)
					.ExecuteCommand() > 0;
		}

		public static List<Feedback> Select(ref int records, int page, int limit, string userName, int typeId = 0, string name = "")
		{
			var list = Instance
				.Queryable<Feedback>()
				.Where(g => g.UserName == userName)
				.WhereIF(typeId > 0, g => g.TypeId == typeId)
				.WhereIF(!string.IsNullOrEmpty(name), g => g.Name.Contains(name))
				.OrderBy(g => g.Id, SqlSugar.OrderByType.Desc)
				.ToPageList(page, limit, ref records);
			var types = FeedbackTypeDal.Types;

			list.ForEach(item =>
			{
				var type = FeedbackTypeDal.Types.FirstOrDefault(t => t.Id == item.TypeId);

				if (type != null)
				{
					item.TypeName = type.Name;
				}
			});

			return list;
		}
	}
}
